package com.qf.thread.then;

import java.util.concurrent.*;

public class AllofDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 创建一个线程池
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                5,
                20,
                2000,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(10000),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()
        );

        // 1.准备任务1
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("任务1执行结束");
            return "任务1";
        }, executor);

        // 2.准备任务2
        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("任务2执行结束");
            return "任务2";
        }, executor);

        // 3.准备任务3
        CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("任务3执行结束");
            return "任务3";
        }, executor);

        // 等前面三个任务全部完成后再去执行任务4
//        CompletableFuture<Void> future4 = CompletableFuture.allOf(future1, future2, future3);
//        future4.get(); // 等待所有任务全部完成后才有返回，阻塞

        // 前面三个任务只要有一个完成，就去执行新的任务
        CompletableFuture<Object> objectCompletableFuture = CompletableFuture.anyOf(future1, future2, future3);
        objectCompletableFuture.get();
        System.out.println("这句话输出说明前面三个任务中有一个已经完成了");
    }
}
